﻿using System;
using System.Collections.Generic;
using Microsoft.Ajax.Utilities;
using SmartContentModule.Helpers;

namespace SmartContentModule.CssModel
{
    internal class CssParseHelper
    {
        List<string> urls = new List<string>();
        List<string> urlsMatchTest = new List<string>();

        /// <summary>
        /// Parses url's from file content and stores them in a string array
        /// </summary>
        /// <param name="cssFileContent">Css file content</param>
        /// <returns>String array containing url's</returns>
        public string[] ParseUrls(string cssFileContent)
        {
            CssParser parser = new CssParser();
            parser.OnTokenRead += new OnTokenReadDelegate(OnTokenRead);
            parser.Parse(cssFileContent);
            return urls.ToArray();
        }

        private void OnTokenRead(CssToken token)
        {
            if (token.TokenType == TokenType.Uri)
            {
                if (!urlsMatchTest.Contains(token.Text.ToLowerInvariant()))
                {
                    urls.Add(token.Text);
                    urlsMatchTest.Add(token.Text.ToLowerInvariant());
                }
            }
        }

        /// <summary>
        /// Get file url form a css url. Forex. returns FullPath\Content\Images\sample.png for url(../../Images/sample.png)
        /// </summary>
        /// <param name="cssUrl">url in css, such as url(../../Images/sample.png)</param>
        /// <param name="directory">Directory for css file</param>
        /// <returns>Returns file path referenced in css url</returns>
        public string GetUrlFromCssUrl(string cssUrl, string directory)
        {
            int urlIndex = cssUrl.IndexOf("url(");
            if (urlIndex < 0)
                return IOHelper.GetFilePath(cssUrl, directory);

            string cssValue = cssUrl.Substring(urlIndex);
            int closingTagIndex = cssValue.IndexOf(")");
            try
            {
                cssValue = cssValue.Substring(4, closingTagIndex - 4);
                if (cssValue.Contains("?"))
                    cssValue = cssValue.Substring(0, cssValue.IndexOf("?"));
            }
            catch (Exception ex)
            {
                ExceptionHelper.HandleError("GetUrlFromCssUrl method failed for url " + cssUrl + " and directory " + directory + " with exception : ", ex);
            }
            return cssValue;
        }
    }
}
